#include "properties.h"
#include <cstdio>
#include <cstring>
#include <iostream>
#include <sstream>

using namespace std;

bool Properties::Init(const char *properties_file)
{
    FILE *pf = fopen(properties_file, "r");
    if (!pf)
    {
        cout << properties_file << " not exist..." << endl;
        return false;
    }
    file_path_ = properties_file;
    fseek(pf, 0, SEEK_END);
    long pf_size = ftell(pf);
    char *buff = new char[pf_size];
    rewind(pf);
    int len = fread(buff, 1, pf_size, pf);

    if (len <= 0 || len != pf_size)
    {
        delete[] buff;
        fclose(pf);
        return false;
    }

    string propertise_txt(buff, pf_size);
    int start = 0;
    int end = 0;
    while ((end = propertise_txt.find('\n', start)) != string::npos)
    {
        string prop = propertise_txt.substr(start, end - start);
        Fill(prop);
        start = end + 1;
    }
    string prop = propertise_txt.substr(start, pf_size - start);
    Fill(prop);
    delete[] buff;
    fclose(pf);
    return true;
}

bool Properties::HasKey(const char *key)
{
    for (int index = 0; index < keys_.size(); ++index)
    {
        if (strcmp(keys_[index].c_str(), key) == 0)
        {
            return true;
        }
    }
    return false;
}

string Properties::Key(const char *key)
{
    for (int index = 0; index < keys_.size(); ++index)
    {
        if (strcmp(keys_[index].c_str(), key) == 0)
        {
            return vals_[index];
        }
    }
    return "";
}

void Properties::Add(const char *key, const char *val)
{
    for (int index = 0; index < keys_.size(); index++)
    {
        if (strcmp(keys_[index].c_str(), key) == 0)
        {
            string val_str(val);
            vals_[index] = val_str;
            return;
        }
    }
    keys_.push_back(key);
    vals_.push_back(val);
    size_++;
}

int Properties::size() const
{
    return size_;
}

string Properties::ToString()
{
    stringstream ss;
    ss << file_path_ << '\n';
    for (int index = 0; index < size_; ++index)
    {
        ss << "(" << (index + 1) << ") " << keys_[index] << "=" << vals_[index] << '\n';
    }
    return ss.str();
}

void Properties::Fill(string &prop)
{
    int pos = prop.find('=');
    if (pos == string::npos)
    {
        return;
    }
    string key = prop.substr(0, pos);
    string val = prop.substr(pos + 1, prop.length());
    if (key.empty() || val.empty())
    {
        return;
    }
    for (int index = 0; index < keys_.size(); index++)
    {
        if (keys_[index] == key)
        {
            vals_[index] = val;
            return;
        }
    }
    keys_.push_back(key);
    vals_.push_back(val);
    size_++;
}

string Properties::Key(int index)
{
    if (index < size_)
    {
        return keys_[index];
    }
    return "";
}

string Properties::Val(int index)
{
    if (index < size_)
    {
        return vals_[index];
    }
    return "";
}